package com.eling.elcms.system.service.impl;

import com.eling.elcms.system.service.ISerialNnumber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;

@Service
@Transactional
public class SerialNumberImpl implements ISerialNnumber,BeanFactoryAware{
	
	private static final Logger log = LoggerFactory.getLogger(SerialNumberImpl.class);
	private BeanFactory beanFactory;
	private JdbcTemplate jdbcTemplate;
	private final String selectSql = "select nextval from bd_serialnumber where seed= ? for update";
	private final String insertSql = "insert into bd_serialnumber  (nextval, seed) values (2,?)";
	private final String updateSql = "update bd_serialnumber set nextval = nextval + 1 where seed= ? ";

	@Override
	public int getSerialNnumber(String seed) {
		Integer nextVal = selectNextVal(seed);
		if (null == nextVal) {
			addSeed(seed);
			return 1;
		} else {
			increaseNextVal(seed);
			return nextVal;
		}
	}
	
	private Integer selectNextVal(String seed){
		Integer nextVal=null;
		try {
			nextVal= getJdbcTemplate().queryForObject(selectSql, Integer.class, seed);
		} catch (EmptyResultDataAccessException e) {
			log.debug("未找到seed为{}的序列",seed);
		}
		log.debug("根据seed={}查询序列, nextVal = {}", seed, nextVal);
		return nextVal;
	}
	
	private void addSeed(String seed) {
		getJdbcTemplate().update(insertSql, seed);
		log.debug("新增序列seed={}",seed);
	}

	private void increaseNextVal(String seed) {
		getJdbcTemplate().update(updateSql, seed);
		log.debug("根据seed={}自增", seed);
	}

	private JdbcTemplate getJdbcTemplate() {
		if (null == jdbcTemplate) {
			DataSource ds = (DataSource) beanFactory.getBean("dataSource");
			jdbcTemplate = new JdbcTemplate(ds);
		}
		return jdbcTemplate;
	}
	
	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.beanFactory = beanFactory;
	}

}
